<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RapidOCR Demo</title>
    <link rel=stylesheet type="text/css" href="/static/css/main.css">
    <link rel="shortcut icon" href="/static/css/favicon.ico" type="image/x-icon"/>
</head>
<body>
    <h1 align="center">
        <b><i>RapidOCR Demo</i></b>&nbsp;
        <a href="https://github.com/RapidAI/RapidOCR" style="font-size: 14px;">欢迎Star</a>&thinsp;
        <a href="https://github.com/RapidAI/RapidOCR/tree/main/ocrweb#readme" style="font-size:14px">了解Demo</a>
    </h1>
    <div class='area'>
        <span class="btn-gen" onclick="javascript:$('#rapid_ocr').click();">试试你的图片?（可拖拽、粘贴、点击）</span>
        <input type="file" style="display: none;" name="pic" id="rapid_ocr"/>
        <span class="uplodNote">支持PNG、JPG、JPEG、BMP，图片大小不超过3M。</span>
    </div>
    <br/>
    <div class="area">
        <div class="leftarea" id="detectDiv">
            <span class="span_title">文 本 检 测 结 果</span><br/><br/>
            <div class="wrapper" id="wrapper" hidden></div>
            <img id="detect_img" src=""/>
        </div>

        <div class="rightarea" id="recogDiv">
            <span id="rec_res" class="span_title">文 本 识 别 结 果</span>
            <br/><br/>
            <table id="locTable" class="table" cellspacing="0" cellpadding="5"></table>
        </div>
    </div>
    <script src="{{url_for('static', filename='js/jquery-3.0.0.min.js')}}"></script>
    <script type="text/javascript">
        // 页面加载时，执行
        var targetFile = null;
        window.onload = function () {
            $('#detect_img').attr("width", "");
            $('#detect_img').attr("height", "");
        }

        $("#rapid_ocr").on('change', function (){
            targetFile = document.getElementById("rapid_ocr").files[0];
            requestOCR();
        });

        $("html").on("dragover", function(event) {
            event.preventDefault();
            event.stopPropagation();
            $(this).addClass('dragging');
        });

        $("html").on("dragleave", function(event) {
            event.preventDefault();
            event.stopPropagation();
            $(this).removeClass('dragging');
        });

        $("html").on("drop", function(event) {
            event.preventDefault();
            event.stopPropagation();
            let trans = event.originalEvent.dataTransfer;
            handleData(trans);
        });

        $('html').on('paste', function (e) {
            let trans = e.originalEvent.clipboardData;
            handleData(trans);
        });

        function handleData(trans) {
            if (trans.items) {
                for (let i = 0; i < trans.items.length; i++) {
                    // If dropped items aren't files, reject them
                    if (trans.items[i].kind === 'file') {
                        targetFile = trans.items[i].getAsFile();
                        console.log(`handleData: items[${i}].name = ${targetFile.name}`);
                        requestOCR();
                        return;
                    }
                }
            } else {
                // Use DataTransfer interface to access the file(s)
                for (let i = 0; i < trans.files.length; i++) {
                    targetFile = trans.files[i];
                    console.log(`handleData: files[${i}].name = ${targetFile.name}`);
                    requestOCR();
                    return;
                }
            }
        }

        function requestOCR(){
            if (!targetFile){
                return;
            }

            // 判断图像格式是否匹配
            let imageName = targetFile.name;
            let index = imageName.lastIndexOf('.');
            let extName = imageName.substr(index + 1);
            let imgArr = ['jpg', 'bmp', 'png', 'jpeg'];
            if (!(imgArr.includes(extName.toLocaleLowerCase()))){
                alert("图像文件格式不支持！");
                return;
            }

            // 判断图像大小是否符合
            let imageSize = targetFile.size / 1024 / 1024;
            if (imageSize >= 3) {
                alert("图像大小超过3M！");
                return;
            }

            var reader = new FileReader();
            reader.onload = function(e){
                var upload_data = {"file": reader.result};
                $.ajax(
                {
                    url:"/ocr",
                    type:"POST",
                    data: JSON.stringify(upload_data),
                    contentType: 'application/json; charset=UTF-8',
                    dataType: 'json',

                    beforeSend:function(){
                        $("#detect_img").attr('src', reader.result);
                        $("#detect_img").attr("width", "95%");
                        $("#detect_img").attr("height", "100%");

                        $("#wrapper").show();
                        $("#locTable").hide();
                        $("#rec_res").html("文本识别结果");
                    },

                    success:function (data) {
                        $("#wrapper").hide();
                        if (data){
                            if (data['image']){
                                $("#detect_img").attr('src', 'data:image/jpeg;base64,'+ data['image']);
                                $('#detect_img').show();
                            }

                            if (data["total_elapse"]){
                                document.getElementById("rec_res").textContent = "文 本 识 别 结 果(Total:" + String(data["total_elapse"]) + "s)"
                                $("#rec_res").show();
                            }

                            if (data["rec_res"]){
                                var rec_res = JSON.parse(data["rec_res"]);

                                // console.log(data['elapse_part']);
                                if (data['elapse_part']){
                                    var elapse_list = data['elapse_part'].split(',');
                                }else{
                                    var elapse_list = [0, 0, 0];
                                }
                                var data = "";
                                data += "<tr>" +
                                            '<th align="right">Det: ' + elapse_list[0] + 's</th>' +
                                            '<th align="center">Cls: ' + elapse_list[1] + 's</th>' +
                                            '<th align="left">Rec: ' + elapse_list[2] + 's</th>' +
                                        "</tr>"
                                data += "<tr>" +
                                            '<th bgcolor="#C0C0C0">序号</th>' +
                                            '<th bgcolor="#C0C0C0">识别结果</th>' +
                                            '<th bgcolor="#C0C0C0">置信度</th>' +
                                        "</tr>"
                                for (let i = 0; i < rec_res.length; i++) {
                                    const element = rec_res[i];
                                    let num = element[0];

                                    let rec_result = element[1];

                                    let score = Number(element[2]);
                                    score = score.toFixed(4);

                                    data += "<tr>"
                                    data += "<td>" + num + "</td>";
                                    data += "<td align='left'>" + rec_result + "</td>";
                                    data += "<td>" + score + "</td>";
                                    data += "</tr>"
                                }
                                document.getElementById("locTable").innerHTML = data;
                                $("#locTable").show();
                            }
                        }

                    }
                }
            );
            }
            reader.readAsDataURL(targetFile)
        }
    </script>
</body>
</html>